<template>
  <div>
    <button
      v-if="canIUse"
      open-type="getUserInfo"
      type="primary"
      @getuserinfo="bindGetUserInfo"
    >
      授权登录
    </button>
    <view v-else>请升级微信版本</view>
  </div>
</template>

<script>
export default {
  data () {
    return {
      canIUse: wx.canIUse('button.open-type.getUserInfo'),
      userInfo: undefined
    }
  },
  methods: {
    navigatetoFunctions () {
      wx.navigateTo({
        url: '/pages/functions/main'
      })
    },
    bindGetUserInfo(e) {
      const { userInfo } = e.mp.detail
      this.userInfo = userInfo
      if (this.userInfo) {
        this.navigatetoFunctions()
      }
    }
  },
  onLoad () {
    // 查看是否授权
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success: (res) => {
              this.userInfo = res.userInfo
              if (this.userInfo) {
                // success使用箭头函数，注意this的指向
                this.navigatetoFunctions()
              }
            }
          })
        }
      }
    })
  }
}
</script>

<style scoped>
  button {
    /* width: 80%; */
  }
</style>